package com.glls.gateway.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

/**
 * TODO
 *
 * @author junyang
 * @version 1.0.0
 * @date 2025/2/21 16:10
 */
@Component
public class MyHeaderRoutePredicateFactory extends AbstractRoutePredicateFactory<MyConfig> {

    public MyHeaderRoutePredicateFactory() {
        super(MyConfig.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(MyConfig config) {
        return new Predicate<ServerWebExchange>() {

            // 自定义断言  返回值 为true   断言放行   否则 断言拦截
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {

                //获取 名字叫 key 的  请求头的值
                String header = serverWebExchange.getRequest().getHeaders().getFirst(config.getKey());

                if(Objects.isNull(header)){
                    return false;
                }

                if(header.equals(config.getValue())){
                    return true;
                }else{
                    return false;
                }


            }
        };
    }


    @Override
    public List<String> shortcutFieldOrder() {

        //- MyHeader=bbb,cccc
        //[bbb,cccc]
        //bbb赋值给MyConfig#key
        //cccc赋值给MyConfig#value

        return Arrays.asList("key","value");
    }
}
